package com.harmontronics.hanma.paas.paas.interceptor;

import com.harmontronics.hanma.paas.paas.consts.DbConstants;
import com.harmontronics.hanma.paas.paas.service.DynamicDataSourceAppService;
import com.harmontronics.hanma.paas.paas.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ldb
 */
public class AppDataSourceLoadInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private DynamicDataSourceAppService dynamicDataSourceAppService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appUnique = RequestUtils.getAppUnique();
        if(!StringUtils.hasLength(appUnique)|| DbConstants.DS_MASTER_NAME.equals(appUnique)){
            return true;
        }

        dynamicDataSourceAppService.createIfAbsent(appUnique.split("_")[1]);

        return true;
    }
}
